package com.lingjtx.common.captcha;

import com.alibaba.fastjson2.JSON;
import com.lingjtx.common.core.RedisOptions;
import com.lingjtx.common.core.algorithm.RSAUtil;
import com.lingjtx.common.core.constant.Const;
import com.lingjtx.common.core.util.CommonUtil;
import com.lingjtx.common.core.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Objects;
import java.util.Random;

public class BlockPuzzleCaptcha implements CaptchaHandle {

    public static final Logger log = LoggerFactory.getLogger(BlockPuzzleCaptcha.class);

    @Override
    public CaptchaVo generator(RedisOptions redis) {

        //原生图片
        BufferedImage originalImage = ImageUtil.getOriginal();
        if (null == originalImage) {
            log.error("滑动底图未初始化成功，请检查路径");
            return null;
        }
        //设置水印
        Graphics backgroundGraphics = originalImage.getGraphics();
        int width = originalImage.getWidth();
        int height = originalImage.getHeight();
        backgroundGraphics.setFont(getWaterMarkFont());
        backgroundGraphics.setColor(Color.white);
        backgroundGraphics.drawString(waterMark, width - getEnOrChLength(waterMark), height - (HAN_ZI_SIZE / 2) + 7);

        //抠图图片
        String jigsawImageBase64 = ImageUtil.getslidingBlock();
        BufferedImage jigsawImage = ImageUtil.getBase64StrToImage(jigsawImageBase64);
        if (null == jigsawImage) {
            log.error("滑动底图未初始化成功，请检查路径");
            return null;
        }
        long start = System.currentTimeMillis();
        CaptchaVo captcha = pictureTemplatesCut(originalImage, jigsawImage, jigsawImageBase64, redis);
        long end = System.currentTimeMillis();
        log.info("耗时：{}", (end - start));
        if (captcha == null || StringUtil.isEmpty(captcha.getMv()) || StringUtil.isEmpty(captcha.getBg())) {
            return null;
        }
        captcha.setCaptchaType(CaptchaType.BLOCK_PUZZLE.toString());
        return captcha;
    }

    @Override
    public String valid(String captchaUid, String pointJson, RedisOptions redis) {
        String rdsKey = String.format(CaptchaHandle.REDIS_CAPTCHA_KEY, captchaUid);
        CaptchaVo captcha = (CaptchaVo) redis.get(rdsKey);
        if (captcha != null) {
            redis.delete(rdsKey); // 验证码只用一次，即刻失效
            PointVo point = captcha.getPoint();
            String paramJson = RSAUtil.decryptByDefaultKey(pointJson);
            PointVo paramPoint = JSON.parseObject(paramJson, PointVo.class);
            if (paramPoint != null) {
                // x坐标在一定误差范围内有效 [x ± slipOffset]
                if (point.x - slipOffset < paramPoint.x
                        && paramPoint.x < point.x + slipOffset
                        && point.y == paramPoint.y) { // 有效范围内
                    String authenticate = StringUtil.getUuid();
                    String secondKey = String.format(CaptchaHandle.REDIS_SECOND_CAPTCHA_KEY, authenticate);
                    redis.set(secondKey, captchaUid, EXPIRESIN_THREE);
                    return authenticate;
                }
            }
        }
        return null;
    }

    /**
     * 根据模板切图
     */
    private CaptchaVo pictureTemplatesCut(BufferedImage originalImage, BufferedImage jigsawImage, String jigsawImageBase64, RedisOptions redis) {
        int originalWidth = originalImage.getWidth();
        int originalHeight = originalImage.getHeight();
        int jigsawWidth = jigsawImage.getWidth();
        int jigsawHeight = jigsawImage.getHeight();

        //随机生成拼图坐标
        PointVo point = generateJigsawPoint(originalWidth, originalHeight, jigsawWidth, jigsawHeight);
        int x = point.getX();
        int y = point.getY();

        //生成新的拼图图像
        BufferedImage newJigsawImage = new BufferedImage(jigsawWidth, jigsawHeight, jigsawImage.getType());
        Graphics2D graphics = newJigsawImage.createGraphics();

        int bold = 5;
        //如果需要生成RGB格式，需要做如下配置,Transparency 设置透明
        newJigsawImage = graphics.getDeviceConfiguration().createCompatibleImage(jigsawWidth, jigsawHeight, Transparency.TRANSLUCENT);
        // 新建的图像根据模板颜色赋值,源图生成遮罩
        cutByTemplate(originalImage, jigsawImage, newJigsawImage, x, 0);

        int position = 0;

        if (captchaInterferenceOptions) {
            if (originalWidth - x - 5 > jigsawWidth * 2) {
                //在原扣图右边插入干扰图
                position = CommonUtil.randomScope(x + jigsawWidth + 5, originalWidth - jigsawWidth);
            } else {
                //在原扣图左边插入干扰图
                position = CommonUtil.randomScope(100, x - jigsawWidth - 5);
            }
        } else {
            position = CommonUtil.randomScope(jigsawWidth, 100 - jigsawWidth);
        }
        while (true) {
            String s = ImageUtil.getslidingBlock();
            if (!jigsawImageBase64.equals(s)) {
                interferenceByTemplate(originalImage, Objects.requireNonNull(ImageUtil.getBase64StrToImage(s)), position, 0);
                break;
            }
        }

        // 设置“抗锯齿”的属性
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        graphics.setStroke(new BasicStroke(bold, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));
        graphics.drawImage(newJigsawImage, 0, 0, null);
        graphics.dispose();

        //新建流。
        try (ByteArrayOutputStream oriImagesOs = new ByteArrayOutputStream(); ByteArrayOutputStream mvImageOs = new ByteArrayOutputStream()) {
            ImageIO.write(originalImage, "jpg", oriImagesOs);//利用ImageIO类提供的write方法，将bi以jpg图片的数据模式写入流。
            byte[] oriCopyImages = oriImagesOs.toByteArray();

            ImageIO.write(newJigsawImage, "png", mvImageOs);//利用ImageIO类提供的write方法，将bi以png图片的数据模式写入流。
            byte[] jigsawImages = mvImageOs.toByteArray();

            CaptchaVo captcha = new CaptchaVo();
            captcha.setCaptchaUid(StringUtil.getUuid());
            captcha.setBgByteStream(oriCopyImages);
            captcha.setMvByteStream(jigsawImages);
            captcha.setBg(Const.SERVER_URL + "/user/captcha/image/bg/" + captcha.getCaptchaUid());
            captcha.setMv(Const.SERVER_URL + "/user/captcha/image/mv/" + captcha.getCaptchaUid());
            captcha.setPoint(point);

            //将坐标信息存入redis中
            String rdsKey = String.format(REDIS_CAPTCHA_KEY, captcha.getCaptchaUid());
            redis.set(rdsKey, captcha, EXP_SECONDS);
            log.debug("CaptchaUid：{},point:{}", captcha.getCaptchaUid(), JSON.toJSONString(point));

            // 接口不返回这些重要数据，只在服务器缓存
            captcha.setBgByteStream(null);
            captcha.setMvByteStream(null);
            captcha.setPoint(null);
            return captcha;
        } catch (Exception e) {
            log.error("生成切图异常：{}", e.getMessage());
            return null;
        }
    }

    /**
     * 随机生成拼图坐标
     */
    private static PointVo generateJigsawPoint(int originalWidth, int originalHeight, int jigsawWidth, int jigsawHeight) {
        Random random = new Random();
        int widthDifference = originalWidth - jigsawWidth;
        int heightDifference = originalHeight - jigsawHeight;
        int x, y = 0;
        if (widthDifference <= 0) {
            x = 5;
        } else {
            x = random.nextInt(originalWidth - jigsawWidth - 100) + 100;
        }
        if (heightDifference <= 0) {
            y = 5;
        } else {
            y = random.nextInt(originalHeight - jigsawHeight) + 5;
        }
        return new PointVo(x, y);
    }

    /**
     * @param oriImage      原图
     * @param templateImage 模板图
     * @param newImage      新抠出的小图
     * @param x             随机扣取坐标X
     * @param y             随机扣取坐标y
     * @throws Exception
     */
    private static void cutByTemplate(BufferedImage oriImage, BufferedImage templateImage, BufferedImage newImage, int x, int y) {
        //临时数组遍历用于高斯模糊存周边像素值
        int[][] martrix = new int[3][3];
        int[] values = new int[9];

        int xLength = templateImage.getWidth();
        int yLength = templateImage.getHeight();
        // 模板图像宽度
        for (int i = 0; i < xLength; i++) {
            // 模板图片高度
            for (int j = 0; j < yLength; j++) {
                // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
                int rgb = templateImage.getRGB(i, j);
                if (rgb < 0) {
                    newImage.setRGB(i, j, oriImage.getRGB(x + i, y + j));

                    //抠图区域高斯模糊
                    readPixel(oriImage, x + i, y + j, values);
                    fillMatrix(martrix, values);
                    oriImage.setRGB(x + i, y + j, avgMatrix(martrix));
                }

                //防止数组越界判断
                if (i == (xLength - 1) || j == (yLength - 1)) {
                    continue;
                }
                int rightRgb = templateImage.getRGB(i + 1, j);
                int downRgb = templateImage.getRGB(i, j + 1);
                //描边处理，,取带像素和无像素的界点，判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
                if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0)) {
                    newImage.setRGB(i, j, Color.white.getRGB());
                    oriImage.setRGB(x + i, y + j, Color.white.getRGB());
                }
            }
        }

    }

    /**
     * 干扰抠图处理
     *
     * @param oriImage      原图
     * @param templateImage 模板图
     * @param x             随机扣取坐标X
     * @param y             随机扣取坐标y
     * @throws Exception
     */
    private static void interferenceByTemplate(BufferedImage oriImage, BufferedImage templateImage, int x, int y) {
        //临时数组遍历用于高斯模糊存周边像素值
        int[][] martrix = new int[3][3];
        int[] values = new int[9];

        int xLength = templateImage.getWidth();
        int yLength = templateImage.getHeight();
        // 模板图像宽度
        for (int i = 0; i < xLength; i++) {
            // 模板图片高度
            for (int j = 0; j < yLength; j++) {
                // 如果模板图像当前像素点不是透明色 copy源文件信息到目标图片中
                int rgb = templateImage.getRGB(i, j);
                if (rgb < 0) {
                    //抠图区域高斯模糊
                    readPixel(oriImage, x + i, y + j, values);
                    fillMatrix(martrix, values);
                    oriImage.setRGB(x + i, y + j, avgMatrix(martrix));
                }
                //防止数组越界判断
                if (i == (xLength - 1) || j == (yLength - 1)) {
                    continue;
                }
                int rightRgb = templateImage.getRGB(i + 1, j);
                int downRgb = templateImage.getRGB(i, j + 1);
                //描边处理，,取带像素和无像素的界点，判断该点是不是临界轮廓点,如果是设置该坐标像素是白色
                if ((rgb >= 0 && rightRgb < 0) || (rgb < 0 && rightRgb >= 0) || (rgb >= 0 && downRgb < 0) || (rgb < 0 && downRgb >= 0)) {
                    oriImage.setRGB(x + i, y + j, Color.white.getRGB());
                }
            }
        }

    }

    private static void readPixel(BufferedImage img, int x, int y, int[] pixels) {
        int xStart = x - 1;
        int yStart = y - 1;
        int current = 0;
        for (int i = xStart; i < 3 + xStart; i++) {
            for (int j = yStart; j < 3 + yStart; j++) {
                int tx = i;
                if (tx < 0) {
                    tx = -tx;

                } else if (tx >= img.getWidth()) {
                    tx = x;
                }
                int ty = j;
                if (ty < 0) {
                    ty = -ty;
                } else if (ty >= img.getHeight()) {
                    ty = y;
                }
                pixels[current++] = img.getRGB(tx, ty);
            }
        }
    }

    private static void fillMatrix(int[][] matrix, int[] values) {
        int filled = 0;
        for (int i = 0; i < matrix.length; i++) {
            int[] x = matrix[i];
            for (int j = 0; j < x.length; j++) {
                x[j] = values[filled++];
            }
        }
    }

    private static int avgMatrix(int[][] matrix) {
        int r = 0;
        int g = 0;
        int b = 0;
        for (int i = 0; i < matrix.length; i++) {
            int[] x = matrix[i];
            for (int j = 0; j < x.length; j++) {
                if (j == 1) {
                    continue;
                }
                Color c = new Color(x[j]);
                r += c.getRed();
                g += c.getGreen();
                b += c.getBlue();
            }
        }
        return new Color(r / 8, g / 8, b / 8).getRGB();
    }
}
